package org.mtmi.gestures;

import org.eclipse.swt.widgets.Display;
import org.mtmi.tuio.Trace;
import org.mtmi.tuio.CursorPoint.States;
import org.mtmi.tuio.listeners.SingleTapListener;
import org.mtmi.tuio.listeners.TUIOTapEvent;
import org.mtmi.ui.controls.ITouchableControl;



public class TouchUpGesture implements IGesture {

	private ITouchableControl target;
	private Trace trace;
	
	public TouchUpGesture(Trace trace) {
		this.trace = trace;
		this.target = trace.getInitialTarget();
	}

	public static boolean detectFromTrace(Trace trace) {
	
		// If cursor moved this is not a click or double click.
		if (trace.getLast().getM_state() == States.UPDATED) {
			return false;
		}
		
		
		// If we have 2 cursor points in the trace and the last one is in REMOVED state
		// we have a Touch Up gesture. (A click tough ...).
		if ((trace.count() == 2) && (trace.getLast().getM_state() == States.REMOVED)) {
			return true;
		}
		
		
	
		return false;
	}

	@Override
	public String getName() {
		return "TouchUpGesture";
	}
	
	@Override
	public GestureType getGestureType() {
		return GestureType.TOUCH_UP_GESTURE;
	}

	@Override
	public void notifyTarget() {
		if (this.target instanceof SingleTapListener) {
			
			final SingleTapListener finalTarget = (SingleTapListener) target;
			
			Display.getDefault().asyncExec(new Runnable() {
				
				@Override
				public void run() {
					finalTarget.tapUp(new TUIOTapEvent((int)trace.getLast().getX(), (int)trace.getLast().getY()));					
				}
			});
		}
		
	}
}
